<template>
  <div id="map"></div>
</template>

<script setup>
import "ol/ol.css";
import Map from "ol/Map";
import View from "ol/View";
import XYZ from "ol/source/XYZ";
import Feature from "ol/Feature";
import TileLayer from "ol/layer/Tile";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import Point from "ol/geom/Point";
import LineString from "ol/geom/LineString";
import { fromLonLat } from "ol/proj";
import { Circle, Fill, Stroke, Style } from "ol/style";
import { onMounted } from "@vue/runtime-core";
import nansha_data from "@/components/openlayers/draw-feature/nansha_data";

let map;

// 创建地图容器
function initMap() {
  map = new Map({
    target: "map",
    // 天地图
    layers: [
      new TileLayer({
        source: new XYZ({
          url: "http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}",
        }),
      }),
    ],
    view: new View({
      center: fromLonLat([113.44, 22.73]),
      zoom: 10,
    }),
  });
}
// 绘制线要素
function addLine() {
  var source = new VectorSource({ wrapX: false });

  var vector = new VectorLayer({
    source: source,
  });

  const lineFeature = [];
  for (let i = 0; i <= nansha_data.pipe_vertices.length - 1; i++) {
    let res = [];
    nansha_data.pipe_vertices[i].forEach((item) => {
      res.push(fromLonLat([item[1], item[0]]));
    });
    var featureLine = new Feature({
      geometry: new LineString(res),
      dashOffset: 0,
    });
    var outlineStroke = new Style({
      stroke: new Stroke({
        color: [25, 25, 255, 1],
        width: 5,
      }),
    });

    // use style caching in production
    function getAnimationStrokeStyle() {
      return new Style({
        stroke: new Stroke({
          color: [204, 204, 255, 1],
          width: 3,
          lineDash: [2, 7],
          lineDashOffset: featureLine.get("dashOffset"),
        }),
      });
    }

    function getStyle() {
      return [outlineStroke, getAnimationStrokeStyle()];
    }

    featureLine.setStyle(getStyle);

    source.addFeature(featureLine);
    lineFeature.push(featureLine);
  }

  map.addLayer(vector);

  // animate the line by constantly adjusting the dashOffset
  // because the offset is stored as a property on the feataure,
  // setting it will cause a refresh which will redraw using the
  // new value
  setInterval(function () {
    lineFeature.forEach((featureLine) => {
      let offset = featureLine.get("dashOffset");
      offset = offset == 8 ? 0 : offset + 1;
      featureLine.set("dashOffset", offset);
    });
  }, 100);
}

onMounted(() => {
  initMap();
  addLine();
});
</script>

<style scoped>
#map {
  width: 100vw;
  height: 100vh;
}
</style>
